package com.example.sqlSession;

import com.example.config.BoundSql;
import com.example.pojo.Configuration;
import com.example.pojo.MappedStatement;
import com.example.utils.GenericTokenParser;
import com.example.utils.ParameterMapping;
import com.example.utils.ParameterMappingTokenHandler;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, IntrospectionException, InvocationTargetException, InstantiationException {
        // 获取驱动 、地址、用户名、密码  创建数据库连接
        Connection connection = configuration.getDataSource().getConnection();

        // 获取sql 含有占位符 、转换sql语句占位符转为？ 、还需要传值
        String sql = mappedStatement.getSql();

        BoundSql boundSql = getBoundSql(sql);

        // 获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        // 设置参数
        String paramterType = mappedStatement.getParamterType();
        System.out.println("XML中入参类型的全路径："+paramterType);
        Class<?> paramterTypeClass = getClassType(paramterType);

        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();


        for(int i=0 ; i < parameterMappingList.size() ; i++ ){
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            // System.out.println("simpleEcecttor  parameterMapping="+parameterMapping);
            String content = parameterMapping.getContent();
            System.out.println("content="+content);

            // 反射 获取类的全路径
            Field declaredField = paramterTypeClass.getDeclaredField(content);
            // 暴力访问
            declaredField.setAccessible(true);

            Object o = declaredField.get(params[0]);
            System.out.println("params的字段名="+o.toString());
            preparedStatement.setObject(i+1,o);

        }

        //  执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        String resultType = mappedStatement.getResultType();
        System.out.println("resultType 是 "+resultType);
        Class<?> resultTypeClass = getClassType(resultType);


        List<Object> objects = new ArrayList<Object>();

        // 封装返回值 把字段映射到实体类中
        while(resultSet.next()){
            Object o = resultTypeClass.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            for(int i=1 ; i<=metaData.getColumnCount();i++){
                // 字段名
                String columnName = metaData.getColumnName(i);
                // 字段值
                Object value = resultSet.getObject(columnName);
                System.out.println("查询记录字段："+columnName + "   对应的值："+value.toString());
                // 使用反射或内省，根据数据表和实体的对应关系

                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o,value.toString());

            }
            objects.add(o);
            
        }

        return  (List<E>) objects;
    }

    private Class<?> getClassType(String paramterType) throws ClassNotFoundException {

        if(paramterType != null){
            Class<?> aClass = Class.forName(paramterType);return  aClass;

        }
        return null;


    }

    // 1、将#{} 用 ？ 替换 2、给占位符 赋值
    private BoundSql getBoundSql(String sql){

        ParameterMappingTokenHandler parameterMappingTokenHandler =new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);

        String parse = genericTokenParser.parse(sql);
        // 解析出的参数
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();

        BoundSql boundSql = new BoundSql(parse, parameterMappings);

        return boundSql;


    }
}
